package common;

import java.io.*;
import java.net.Socket;

/**
 * @author LinLe
 * @create 2020-12-21 23:10
 */
//数据的处理，实现服务器和客户端之间的通信
public class DataExchange {
    private Socket s;
    private PrintWriter pw;
    private BufferedReader br;
    
    public DataExchange() {
    }
    
    public DataExchange(Socket s) throws IOException {
        this.s = s;
        init(s);
    }
    
    private void init(Socket s) throws IOException {
        pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    }
    //接收功能
    public ChatMessage receive() throws IOException {
        String line = null;
        while(true){
         line = br.readLine();
         if(line != null || line.length()>0 ){
             break;
         }
        }
        return ChatMessage.buildFrom(line);
    }
    //发送功能
    public void send(ChatMessage cm){
        pw.println(cm.toMessageString());
        pw.flush();
    }
    
    public void close(){
        try {
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
